package com.ggb.reactive.task

import com.ggb.reactive.constant.CANCELLED
import com.ggb.reactive.constant.COMPLETED
import com.ggb.reactive.constant.ORDER_TIMEOUT_MSG
import com.ggb.reactive.constant.PENDING_PAYMENT
import com.ggb.reactive.extension.log
import com.ggb.reactive.repository.OrderRepository
import com.ggb.reactive.service.OrderService
import lombok.RequiredArgsConstructor
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.Instant
import java.time.ZoneId
import java.util.*

@Component
@RequiredArgsConstructor
class OrderTask(
    val orderService: OrderService
) {
    /**
     * 处理超时订单的方法
     */
    @Scheduled(cron = "0 * * * * ?") //每分钟执行一次
    fun processTimeoutOrder() {
        val now = Instant.now().atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("GMT+8")).toLocalDateTime()
        log.info("定时处理超时订单：{}", now)
        println("定时处理超时订单：$now")
        val time = Instant.now().plusSeconds(-15 * 60)
        orderService.getByStatusAndOrderTimLT(PENDING_PAYMENT, time)
            .flatMap { order ->
                order.apply {
                    status = CANCELLED
                    cancelReason = ORDER_TIMEOUT_MSG
                    cancelTime = Instant.now()
                }
                orderService.updateOrder(order)
            }
            .subscribe()
    }
    /**
     * 处理超时订单的方法
     */
    @Scheduled(cron="0 0 1 * * ?") // 每天凌晨1点执行
    fun processDeliveryOrder(){
        log.info("定时处理配送中的订单：{}", Instant.now());
        val time = Instant.now().plusSeconds(-15*60)
        orderService.getByStatusAndOrderTimLT(PENDING_PAYMENT,time)
            .flatMap {
                it.apply {
                    status = COMPLETED
                }
                orderService.updateOrder(it)
            }
            .subscribe()
    }
}